package com.github.xzb617.client.route.scg.rules.impl;

import com.github.xzb617.client.route.scg.constant.RouteRule;
import com.github.xzb617.client.route.scg.props.RouteProperties;
import com.github.xzb617.client.route.scg.rules.RoutingRule;
import com.github.xzb617.client.route.scg.rules.ratio.WeightCalculator;
import com.github.xzb617.client.route.scg.utils.RouteUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import java.util.Map;

public class IpRoutingRule implements RoutingRule {

    @Override
    public void matches(ServerHttpRequest request, HttpHeaders httpHeaders, String ipAddr, RouteProperties.RuleProperties config, RoutingRule routingRuleChain) {
        Map<String, Map<String, RouteRule>> rules = config.getRules();
        Map<String, RouteRule> ipRuleMap = rules.get("IP");
        if (ipRuleMap!=null && !ipRuleMap.isEmpty()) {
            RouteRule routeRule = ipRuleMap.get(ipAddr);
            if (routeRule != null) {
                boolean available = WeightCalculator.available(ipAddr, routeRule.getWeight());
                if (available) {
                    // 匹配IP成功，且在权重范围内，打上标签
                    RouteUtil.assignRouteLabel(httpHeaders, routeRule, true);
                } else {
                    RouteUtil.assignRouteLabel(httpHeaders, routeRule, false);
                }
            }
        }
    }

}
